using System;
using System.Collections.Generic;

namespace AvaloniaDrawingPad.Models.Commands
{
    /// <summary>
    /// 删除图层命令
    /// </summary>
    public class RemoveLayerCommand : ICommand
    {
        private readonly LayerManager _layerManager;
        private readonly Layer _layer;
        private readonly int _layerIndex;
        private readonly List<SelectableShape> _selectableShapes;
        private readonly List<SelectableShape> _layerShapes = new List<SelectableShape>();
        
        public string Description => "删除图层";
        
        public RemoveLayerCommand(
            LayerManager layerManager, 
            Layer layer, 
            List<SelectableShape> selectableShapes)
        {
            _layerManager = layerManager;
            _layer = layer;
            _selectableShapes = selectableShapes;
            
            // 获取图层索引
            _layerIndex = _layerManager.Layers.IndexOf(_layer);
            
            // 记录图层中的所有可选择图形
            foreach (var shape in _selectableShapes)
            {
                if (shape.Element.Parent == _layer.Content)
                {
                    _layerShapes.Add(shape);
                }
            }
        }
        
        public void Execute()
        {
            // 从可选择图形列表中移除图层中的所有图形
            foreach (var shape in _layerShapes)
            {
                _selectableShapes.Remove(shape);
            }
            
            // 移除图层
            _layerManager.RemoveLayer(_layer);
            
            // 标记项目已修改
            _layerManager.MarkAsChanged();
        }
        
        public void Undo()
        {
            // 重新添加图层
            _layerManager.InsertLayer(_layerIndex, _layer);
            
            // 重新添加图层中的所有图形到可选择图形列表
            foreach (var shape in _layerShapes)
            {
                if (!_selectableShapes.Contains(shape))
                {
                    _selectableShapes.Add(shape);
                }
            }
            
            // 标记项目已修改
            _layerManager.MarkAsChanged();
        }
    }
} 